//
// Created by iyb-dingfeng on 2018/11/21.
//

#include "tools.h"

std::string jstring2string(JNIEnv *env, jstring jstr) {
    char *rtn = NULL;
    jclass clsstring = env->FindClass("java/lang/String");
    jstring strencode = env->NewStringUTF("GB2312");
    jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
    jbyteArray barr = (jbyteArray) env->CallObjectMethod(jstr, mid, strencode);
    jsize alen = env->GetArrayLength(barr);
    jbyte *ba = env->GetByteArrayElements(barr, JNI_FALSE);
    if (alen > 0) {
        rtn = (char *) malloc(alen + 1);
        memcpy(rtn, ba, alen);
        rtn[alen] = 0;
    }
    env->ReleaseByteArrayElements(barr, ba, 0);
    std::string stemp(rtn);
    free(rtn);

    return stemp;
}

char *string2char(std::string str) {
    std::string s1 = str;
    char *data;
    int len = s1.length();
    data = (char *) malloc((len + 1) * sizeof(char));
    s1.copy(data, len, 0);
    return data;
}

jstring string2jstring(JNIEnv *env, const char *pat) {
    return env->NewStringUTF(pat);
}